<template>
  <div class="project-member">
    <div class="project-member-head">
      <div class="search">
        <el-form inline :model="searchForm" label-width="45px">
          <el-form-item label="姓名:">
            <el-select v-model="searchForm.userId" placeholder="请选择成员" clearable filterable style="width: 200px">
              <el-option
                v-for="item in projectUserList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态:">
            <el-select v-model="searchForm.effectFlag" placeholder="请选择状态" clearable style="width: 200px">
              <el-option v-for="(item, index) in statusList" :key="index" :label="item.label" :value="item.value">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
            <el-button :icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="action">
        <el-tooltip class="box-item" effect="dark" content="新增成员" placement="top-start">
          <el-button @click="handleAdd" plain>
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    <div class="project-member-content">
      <el-table :data="tableData" v-loading="loading" :header-cell-style="tabelHeaderCellStyle" height="100%">
        <el-table-column width="80"></el-table-column>
        <el-table-column show-overflow-tooltip label="姓名" prop="userName"></el-table-column>
        <el-table-column show-overflow-tooltip label="成员角色" prop="pstName"></el-table-column>
        <el-table-column show-overflow-tooltip label="状态" prop="effectFlag">
          <template v-slot="scope">
            <span v-if="scope.row.effectFlag === 1" class="project">项目中</span>
            <span v-if="scope.row.effectFlag === 2" class="leave">已离开</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="开始时间" prop="joinedTime"></el-table-column>
        <el-table-column show-overflow-tooltip label="结束时间" prop="leaveTime"></el-table-column>
        <el-table-column show-overflow-tooltip label="操作" prop="role" width="200px">
          <template v-slot="scope">
            <el-button
              v-if="scope.row.effectFlag === 1"
              text
              type="primary"
              size="small"
              @click="handleView(scope.row)">
              编排
            </el-button>
            <el-button
              v-if="scope.row.effectFlag === 1 && scope.row.pstName !== '项目经理'"
              text
              type="primary"
              size="small"
              @click="handleRelease(scope.row)">
              释放
            </el-button>
            <!--v-if="scope.row.effectFlag === 1"-->
            <!-- <el-button type="text" size="small">查看</el-button> -->
            <el-button
              v-if="scope.row.effectFlag === 2"
              text
              type="primary"
              size="small"
              @click="handlePullIn(scope.row)">
              拉入
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="queryInfo.params.pageNum"
        v-model:page-size="queryInfo.params.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 选择人员 -->
    <PersonnelSelection v-model="personnelVisible" @submit="setMember"></PersonnelSelection>
    <!--人员任务线-->
    <!-- <TaskChatDialog
      v-model="taskTimeLineVisible"
      title="任务线"
      @close="handleTaskLineClose"
      width="661px"
      append-to-body>
      <TaskTimeLine :project-id="props.projectId" :user="currentUser"></TaskTimeLine>
    </TaskChatDialog> -->
    <TaskChatDialog
      v-model="dialogCalendarVisible"
      width="80%"
      class="task-dialog"
      body-class-name="dialog-child-custom"
      destroy-on-close
      fullscreen
      append-to-body>
      <div>
        <el-descriptions :column="4">
          <template #title>{{ projectData.taskUserName }}:</template>
          <el-descriptions-item label="任务总数" :width="80" align="center">
            {{ info.taskInfoTotal }}
          </el-descriptions-item>
          <el-descriptions-item label="已完成" :width="80" align="center">
            {{ info.taskInfoDoneTotal }}
          </el-descriptions-item>
          <el-descriptions-item label="未完成" :width="80" align="center">
            {{ info.taskInfoDoingTotal }}
          </el-descriptions-item>
          <el-descriptions-item label="超期完成" :width="80" align="center">
            {{ info.taskInfoDelayDoneTotal }}
          </el-descriptions-item>
        </el-descriptions>
        <TaskCalendar :calendarData="projectData" disabled />
      </div>
    </TaskChatDialog>
  </div>
</template>
<script setup>
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { getProjectMember, addProjectMember, editProjectMember } from '@/assets/api/project-member'
import { getUserList } from '@/assets/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import useProject from '@/store/project'
import { getTaskListByTime } from '@/assets/api/task'
const projectStore = useProject()
import dayjs from 'dayjs'

const props = defineProps({
  projectId: {
    type: String,
    default: '',
  },
})
const searchForm = ref({})
const tableData = ref([])
const loading = ref(false)
const userList = ref([])
const projectUserList = ref([])

const personnelVisible = ref(false)
const taskTimeLineVisible = ref(false)
const currentUser = ref({})
const statusList = ref([
  { label: '项目中', value: 1 },
  { label: '已离开', value: 2 },
])
function tabelHeaderCellStyle() {
  return { 'background-color': 'var(--elp-color-info-light-9)', color: 'var(--elp-color-black)', fontWeight: '400' }
}
const queryInfo = reactive({
  params: {
    pageSize: 10,
    pageNum: 1,
  },
})
const dataTotal = ref(0)
function handleSizeChange(val) {
  queryInfo.params.pageSize = val
  getList()
}
function handleCurrentChange(val) {
  queryInfo.params.pageNum = val
  getList()
}
// 查询
getUserListData()
function getUserListData() {
  getUserList().then((res) => {
    if (res.code === 200) {
      userList.value = res.rows
    } else {
      ElMessage.error(res.msg)
    }
  })
}
getList()
function getList() {
  loading.value = true
  const params = {
    projectId: props.projectId,
    ...queryInfo.params,
    ...searchForm.value,
  }
  getProjectMember(params)
    .then((res) => {
      if (res.code === 200) {
        tableData.value = res.rows || []
        loading.value = false
        dataTotal.value = res.total
        if (!projectUserList.value.length) projectUserList.value = JSON.parse(JSON.stringify(tableData.value))
      } else {
        ElMessage.error(res.msg)
      }
    })
    .catch(() => {})
}
const projectInfo = ref({})

// 条件查询
function handleSearch() {
  getList()
}
// 重置
function handleReset() {
  searchForm.value = {}
  queryInfo.params.pageSize = 10
  queryInfo.params.pageNum = 1
  getList()
}

const info = ref({})
function getTaskListByTimeData(date, taskUserId) {
  if (date) {
    getTaskListByTime({
      projectId: props.projectId,
      taskUserId,
      planBegintime: dayjs(date[0]).format('YYYY-MM-DD'),
      planEndtime: dayjs(date[1]).format('YYYY-MM-DD'),
    }).then((res) => {
      loading.value = false
      if (res.code === 200) {
        info.value = res.data
      }
    })
  }
}
// 新增
function handleAdd() {
  personnelVisible.value = true
}
// 查看
const dialogCalendarVisible = ref(false)
const projectData = ref({})
function handleView(row) {
  // currentUser.value = row
  // taskTimeLineVisible.value = true
  getTaskListByTimeData([projectStore.getProjectInfo.planBegin, projectStore.getProjectInfo.planEnd], row.userId)
  projectData.value.start = projectStore.getProjectInfo.planBegin
  projectData.value.end = projectStore.getProjectInfo.planEnd
  projectData.value.taskUserId = row.userId
  projectData.value.taskUserName = row.userName
  dialogCalendarVisible.value = true
}

function handleTaskLineClose() {
  currentUser.value = {}
}

function setMember(data) {
  if (data.length > 0) {
    const memberData = data
      .filter((item) => item.userName)
      .map((val) => {
        const value = {}
        value.userId = val.userId
        value.projectId = props.projectId
        return value
      })
    addProjectMember(memberData)
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success('添加成功')
          personnelVisible.value = false
          getList()
        } else {
          ElMessage.error('添加失败')
        }
      })
      .catch(() => {})
  } else {
    personnelVisible.value = false
  }
}
// 其他操作
function handleRelease(row) {
  const data = JSON.parse(JSON.stringify(row))
  ElMessageBox.confirm(`是否确认释放成员【${row.userName}】`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      data.effectFlag = 2
      editProjectMember(data).then((res) => {
        if (res.code === 200) {
          ElMessage.success('释放成功')
          getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    })
    .catch(() => {})
}
function handlePullIn(row) {
  const data = JSON.parse(JSON.stringify(row))
  ElMessageBox.confirm(`是否确认拉入成员【${row.userName}】`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      data.effectFlag = 1
      editProjectMember(data).then((res) => {
        if (res.code === 200) {
          ElMessage.success('拉入成功')
          getList()
        } else {
          ElMessage.error('拉入失败')
        }
      })
    })
    .catch(() => {})
}
</script>
<style lang="scss" scoped>
.project-member {
  height: 100%;
  &-head {
    display: flex;
    justify-content: space-between;
    height: 50px;
    .elp-form-item {
      margin-right: 50px;
    }
    .action {
      .elp-button {
        padding: 10px;
      }
    }
  }
  &-content {
    .elp-table {
      margin-bottom: 20px;
    }
    .elp-pagination {
      justify-content: flex-end;
    }
    height: calc(100% - 100px);
    .project::before {
      background-color: var(--elp-color-primary);
    }
    .leave::before {
      background-color: var(--elp-color-info);
    }
    .project,
    .leave {
      display: flex;
      align-items: center;
      &::before {
        content: ' ';
        display: block;
        width: 8px;
        height: 8px;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }
}

:deep(.elp-descriptions__label) {
  font-weight: bold;
}
</style>
